package com.hezhou.jenkins.my_jenkins_test.exception;

import com.hezhou.jenkins.my_jenkins_test.json.CodeMsg;
import com.hezhou.jenkins.my_jenkins_test.json.HeZhouResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.ResponseUtil;
import org.aspectj.apache.bcel.classfile.Code;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * ---------------------------
 * (GlobalExceptionHandler) 全局异常处理
 * ---------------------------
 *
 * @Author: [hezhou]
 * @Date: 2020/4/23
 * @Version: [1.0.1]
 * ---------------------------
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理自定义的业务异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = MyException.class)
    public HeZhouResult MyExceptionHandler(HttpServletRequest req, MyException e){
        log.error("发生业务异常！原因是：{}",e.getErrorMsg());
        CodeMsg codeMsg = new CodeMsg(CodeMsg.SERVER_EXCEPTION.getRetCode(),req.getMethod()+"发生异常原因为："+e.getErrorMsg());
        return HeZhouResult.error(codeMsg);
    }

    /**
     * 处理空指针的异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =NullPointerException.class)
    public HeZhouResult exceptionHandler(HttpServletRequest req, NullPointerException e){
        log.error("发生空指针异常！原因是:",e);
        CodeMsg codeMsg = new CodeMsg(400,"空指针异常");
        return HeZhouResult.error(codeMsg);
    }

    /**
     * 处理其他异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =Exception.class)
    public HeZhouResult exceptionHandler(HttpServletRequest req, Exception e){
        log.error("未知异常！原因是:",e);
        return HeZhouResult.error(new CodeMsg(CodeMsg.PARAMETER_ISNULL.getRetCode(),CodeMsg.PARAMETER_ISNULL.getMessage()));
    }
}
